package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
	"time"
)

// UnixToTime
//
//	@Description: 时间戳转换为时间字符串
//	@param timestamp
//	@return string
func UnixToTime(timestamp int64) string {
	return time.Unix(timestamp, 0).Format("2006-01-02 15:04:05")
}

// GetDouble
//
//	@Description: 获得两倍大小的数
//	@param num
//	@return int
func GetDouble(num int) int {
	return num * 2
}

// main
//
//	@Description: 路由中间件
func main() {
	r := gin.Default()

	//设置自定义模板函数
	r.SetFuncMap(template.FuncMap{
		"UnixToTime": UnixToTime, //注册模板函数
		"GetDouble":  GetDouble,  //注册模板函数
	})
	r.LoadHTMLGlob("templates/**/*")
	r.Static("/static", "./static")
	//配置路由
	//routers2.UserRouters(r)
	//routers2.CarRouters(r)

	//自定路由的中间件：执行顺序：
	//countTime-start...
	//middleWareMethod-start...
	//access-gin...
	//middleWareMethod-end...
	//countTime-end... 735000
	r.GET("/gin", middleWareMethod00, middleWareMethod01, func(c *gin.Context) {
		time.Sleep(time.Second)
		fmt.Println("access-gin...")
		c.String(http.StatusOK, "gin首页")
	})

	//多个执行顺序 :链式调用
	//countTime-start...
	//middleWareMethod-start...
	//access-news...
	//middleWareMethodEnd-start...
	//middleWareMethodEnd-end...
	//middleWareMethod-end...
	//countTime-end... 535700
	r.GET("/news", middleWareMethod00, middleWareMethod01, func(c *gin.Context) {
		fmt.Println("access-news...")
		c.String(http.StatusOK, "news首页")
	}, middleWareMethodEnd)

	r.Run(":8888")
}

func middleWareMethod00(c *gin.Context) {
	start := time.Now().UnixNano()
	fmt.Println("countTime-start...")
	c.Next()
	end := time.Now().UnixNano()
	fmt.Println("countTime-end...", end-start)
}

func middleWareMethod01(c *gin.Context) {
	fmt.Println("middleWareMethod-start...")
	c.Next() //
	fmt.Println("middleWareMethod-end...")
}

// countTime-start...
// middleWareMethod-start...
// middleWareMethod02-start...
// middleWareMethod02-end...
// middleWareMethod-end...
// countTime-end... 535300
func middleWareMethod02(c *gin.Context) {
	fmt.Println("middleWareMethod02-start...")
	c.Abort() // 中止后面的程序(了解)
	fmt.Println("middleWareMethod02-end...")
}

func middleWareMethodEnd(c *gin.Context) {
	fmt.Println("middleWareMethodEnd-start...")
	c.Next()
	fmt.Println("middleWareMethodEnd-end...")
}
